// pages/storeHome/storeHome.js
import * as API_Store from '../../api/store'
import * as API_Product from '../../api/product'
import * as API_Teach from '../../api/teach'
import * as API_Comment from '../../api/comment'
import * as API_Visit from '../../api/visitRecord'
import * as API_Coupon from '../../api/coupon'
import * as API_Order from '../../api/order'
import * as API_Appointment from '../../api/appointment'
import * as API_Fitment from '../../api/fitment'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponList: [],
    opusCount: 0,
    starList: [, , , , ,],
    opusList: [],
    teachList: [],
    teachListLength: 0,
    productList: [],
    store: {},
    serviceItem: [],
    headshow: 1,
    bacImgs: [],
    videoUrl: '',
    fitment: {},
    params: {
      pageNum: 1,
      pageSize: 10,
      storeId: ''
    },
    id: '',
    commentList: [],
    finished: false,
    total: 0,
    appointmentShowBtn: false,
    section3SelectIndex: 0,
    section3Select: ['预约', '下单'],
    appointment: {
      storeId: '',
      appointmentDate: '',
      appointmentItem: '',
      appointmentNum: 1,
      timeFrame: '',
      technicianId: '',
      appointmentRemark: '',
      appointmentPhone: ''
    },
    serviceList: null,
    dateList: null,
    timeList: null,
    jishiList: null,
    subState: false
  },
  /* 预约相关函数 */
  selectWeekIndex(index) {
    this.setData({ 'appointment.timeFrame': '', timeList: [] })
    let dateList = this.data.dateList;
    let indexfor = 0;
    dateList.forEach(item => {
      if (index == indexfor) {
        item.act = true;

        this.setData({ 'appointment.appointmentDate': item.appointmentDate });
      } else {
        item.act = false;
      }
      indexfor++;
    })
    this.setData({ dateList: dateList });
    this.listCanAppointmentTechnician();
  },
  listCanAppointmentTechnician() {
    let storeId = this.data.appointment.storeId;
    let appointmentDate = this.data.appointment.appointmentDate;
    let params = { storeId: storeId, appointmentDate: appointmentDate };
    API_Appointment.listCanAppointmentTechnician(params).then(res => {
      let jso = res.data;
      let jishiList = jso.jsoCan;
      this.setData({ jishiList: jishiList });
      if (jishiList.length > 0) {
        //  debugger
        let technicianId = this.data.appointment.technicianId;//之前选中的技师
        if (!technicianId) {
          //  之前没有选中技师
          this.setData({ 'appointment.timeFrame': '', 'appointment.technicianId': '' })
          this.selectTechIndex(0);
        } else {
          // 之前有选择技师
          let index = 0;
          let flushIndex = 0;
          jishiList.forEach(item => {
            if (item.id == technicianId) {
              if (item.canSelect) {
                //依然可以选择
                flushIndex = index;
              }
            }
            index++;
          })
          this.selectTechIndex(flushIndex);
        }
      }
    })
  },
  selectTechIndex(index) {
    let jishiList = this.data.jishiList;
    let select = jishiList[index];
    if (!select.canSelect) {
      return;
    }
    this.setData({ 'appointment.timeFrame': '' })
    let indexfor = 0;
    jishiList.forEach(item => {
      if (index == indexfor) {
        item.act = true;
        this.setData({ 'appointment.technicianId': item.id });
      } else {
        item.act = false;
      }
      indexfor++;
    })
    this.setData({ jishiList: jishiList });
    this.listCanAppointmentTimeFrame();
  },
  listCanAppointmentTimeFrame() {
    let storeId = this.data.appointment.storeId;
    let technicianId = this.data.appointment.technicianId;
    let appointmentDate = this.data.appointment.appointmentDate;
    let params = { storeId: storeId, technicianId: technicianId, appointmentDate: appointmentDate };
    API_Appointment.listCanAppointmentTimeFrame(params).then(res => {
      let jso = res.data;
      let timeList = jso.timeList;
      this.setData({ timeList: timeList })
    })
  },
  section3Switch(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      section3SelectIndex: index
    })
  },
  selectWeek(e) {
    let index = e.currentTarget.dataset.index;
    this.selectWeekIndex(index);
  },
  selectTime(e) {
    let index = e.currentTarget.dataset.index;
    this.selectTimeIndex(index);
  },
  selectTimeIndex(index) {
    let timeList = this.data.timeList;
    let indexfor = 0;
    timeList.forEach(item => {
      if (index == indexfor) {
        item.act = true;
        this.setData({ 'appointment.timeFrame': item.name });
      } else {
        item.act = false;
      }
      indexfor++;
    })
    this.setData({ timeList: timeList });
  },
  selectTech(e) {
    let index = e.currentTarget.dataset.index;
    this.selectTechIndex(index);
  },
  numsub() {
    let appointmentNum = this.data.appointment.appointmentNum;
    if (appointmentNum > 1) {
      appointmentNum = appointmentNum - 1;
    }
    this.setData({ 'appointment.appointmentNum': appointmentNum });
  },
  numPlus() {
    let appointmentNum = this.data.appointment.appointmentNum;
    if (appointmentNum < 10) {
      appointmentNum = appointmentNum + 1;
    }
    this.setData({ 'appointment.appointmentNum': appointmentNum });
  },
  phoneChange (e) {
    let appointmentPhone = e.detail.value;
    this.setData({ 'appointment.appointmentPhone': appointmentPhone })
  },
  remarkChange (e) {
    let appointmentRemark = e.detail.value;
    this.setData({ 'appointment.appointmentRemark': appointmentRemark })
  },
  subAppointment() {
    let appointment = this.data.appointment;
    // debugger
    this.setData({ subState: true });
    // if (!appointment.appointmentItem) {
    //   wx.showToast({ title: '请选择预约项目', icon: 'none', duration: 1500 })
    //   this.setData({ subState: false });
    //   return;
    // }
    if (!appointment.appointmentDate) {
      wx.showToast({ title: '请选择预约日期', icon: 'none', duration: 1500 })
      this.setData({ subState: false });
      return;
    }
    // let tteme=!appointment.technicianId;
    // let tteme1=appointment.technicianId!==0;
    // let tteme2= appointment.technicianId===0
    if (!appointment.technicianId && !(appointment.technicianId === 0)) {
      wx.showToast({ title: '请选择预约技师', icon: 'none', duration: 1500 })
      this.setData({ subState: false });
      return;
    }
    if (!appointment.timeFrame) {
      wx.showToast({ title: '请选择预约时段', icon: 'none', duration: 1500 })
      this.setData({ subState: false });
      return;
    }
    if (!appointment.appointmentPhone) {
      wx.showToast({ title: '请填写预约人电话', icon: 'none', duration: 1500 })
      this.setData({ subState: false });
      return;
    }
    if (11 != appointment.appointmentPhone.length) {
      wx.showToast({ title: '请填写正确电话', icon: 'none', duration: 1500 })
      this.setData({ subState: false });
      return;
    }
    API_Appointment.appointment(appointment).then(res => {
      wx.showToast({ title: res.msg, icon: 'none', duration: 1500 })
      if (res.code == 200) {
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/appointmentRecord/appointmentRecord',
          })
        }, 1500);
      } else {
        this.setData({ subState: false });
      }
    })
  },
  /* 预约相关函数 */
  // 更换门店
  switchStore() {
    let pages = getCurrentPages()
    let prevPages = pages[pages.length - 2]
    if (prevPages && prevPages.route === 'pages/productList/productList') {
      wx.navigateBack()
    } else {
      wx.navigateTo({
        url: '/pages/productList/productList'
      })
    }
  },
  // 跳转到视频或相册
  goHomeIndex(e) {
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: '../headImageList/headImageList?id=' + id + '&index=' + index,
    })
  },
  autoplayVideo: function (e) {
    let indexAll = e.currentTarget.dataset.indexAll;
    let commentList = this.data.commentList;
    commentList[indexAll].autoplay = true;
    this.setData({ commentList: commentList });
    // debugger
  },
  autoplayVideo1: function (e) {
    let indexAll = e.currentTarget.dataset.indexAll;
    let opusList = this.data.opusList;
    opusList[indexAll].autoplay = true;
    this.setData({ opusList: opusList });
    // debugger
  },
  autoplayVideo2: function () {
    let fitment = this.data.fitment;
    fitment.autoplay = true;
    this.setData({ fitment: fitment });
    // debugger
  },
  goMessageDetail: function (e) {
    let storeId = this.data.store.id;
    wx.navigateTo({
      url: '../messageDetail/messageDetail?storeId=' + storeId
    })
  },
  goAppointment: function (e) {
    let storeId = this.data.store.id;
    wx.navigateTo({
      url: '../appointment/appointment?storeId=' + storeId
    })
  },
  onPageScroll: function (e) {
    let opacity = 0
    opacity = (100 - (e.scrollTop / 2)) / 100
    this.setData({
      headshow: opacity
    })
  },
  toCommentList: function (e) {
    wx.navigateTo({
      url: '/pages/commentList/commentList?storeid=' + e.currentTarget.dataset.storeid,
    })
  },
  toTechnicianOpus(e) {
    wx.navigateTo({
      url: '/pages/technicianOpus/technicianOpus?storeid=' + e.currentTarget.dataset.storeid,
    })
  },
  goDetail(e) {
    let id = e.currentTarget.dataset.id
    let status = e.currentTarget.dataset.status
    let storeId = e.currentTarget.dataset.storeid
    if (status === 'Y' && getApp().globalData.isVip !== 'Y' && !getApp().globalData.isLookVip) {
      wx.showToast({
        title: '这是会员专享商品！',
        icon: 'none'
      })
    } else {
      wx.navigateTo({
        url: '/pages/productDetail/productDetail?id=' + id + '&storeId=' + storeId,
      })
    }
  },
  toBack: function () {
    wx.navigateBack({
      delta: 0,
    })
  },
  getMyCoupons(data) {
    API_Coupon.getMyStoreCoupons(this.data.id).then(ref => {
      if (ref.data.rows.length > 0) {
        let myList = ref.data.rows
        data = data.map(item => {
          item.getCoupons = 'N'
          return item
        })
        for (let item of myList) {
          for (var i = 0; i < data.length; i++) {
            let coupons = data[i]
            if (item.couponId == coupons.id) {
              coupons.getCoupons = 'Y'
              data[i].getCoupons = 'Y'
            }
          }
        }
      }
      this.setData({
        couponList: data
      })
    })
  },

  initAppointmentShowBtn: function (storeId) {
    let param = { storeId: storeId }
    API_Appointment.showAppointment(param).then(res => {
      if (res.code == 200) {
        let jso = res.data;
        let show = jso.show;
        if ("Y" == show) {
          this.setData({ appointmentShowBtn: true })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let type = parseInt(options.type)
    let globalData = getApp().globalData;
    let statusBarHeight = globalData.systemInfo.statusBarHeight;
    this.setData({ statusBarHeight: statusBarHeight });
    this.initAppointmentShowBtn(options.id);
    API_Coupon.getListCanGet(options.id).then(res => {
      var data = res.data
      this.setData({
        id: options.id
      })
      this.getMyCoupons(data)
    })
    API_Store.getInfo(options.id).then(res => {
      if (res.data) {
        let arr = JSON.parse(res.data.serviceItem)
        let temp = []
        for (var i = 0; i < arr.length; i++) {
          temp.push(arr[i].dictLabel)
        }
        res.data.storeLevel = res.data.storeLevel.toFixed(1)
        res.data.effectLevel = res.data.effectLevel.toFixed(1)
        res.data.environmentLevel = res.data.environmentLevel.toFixed(1)
        res.data.serviceLevel = res.data.serviceLevel.toFixed(1)

        this.setData({
          store: res.data,
          serviceItem: temp,
        })

        API_Fitment.getInfo(res.data.id).then(res => {
          if (res) {
            let imgs = res.picUrl.split(",")
            this.setData({
              bacImgs: imgs,
              fitment: res
            })
          }
        })


        API_Visit.insr(res.data.id).then(() => { })
      }
    })
    let params = {
      storeId: options.id
    }
    API_Teach.getList(params).then(res => {
      let teachList = res.data.rows;
      let teachListLength = 0;
      teachList.forEach(item => {
        teachListLength = item.rowList.length + teachListLength;
      });
      this.setData({
        teachList: teachList,
        teachListLength: teachListLength
      })


      if (res.data.rows.length > 0) {
        let query = {
          storeId: options.id,
          //  techId:res.data.rows[0].rowList[0].techId,
          pageNum: 1,
          pageSize: 4
        }
        API_Teach.getOpusList(query).then(res => {

          this.setData({
            opusList: res.data.rows,
            opusCount: res.data.total
          })
        })
      }
    })
    API_Product.getList(params).then(res => {
      this.setData({
        productList: res.data.rows
      })
    })
    params.pageNum = 1;
    params.pageSize = 20;
    API_Comment.getList(params).then(res => {
      let arr = this.data.commentList

      for (let item of res.data.rows) {

        let arr = [];
        if (item.commentImages) {
          arr = item.commentImages.split(",");
        }

        let arrvideo = [];
        if (item.commentVideo) {
          arrvideo = item.commentVideo.split(",");
        }

        item.commentImages = arr
        item.commentVideo = arrvideo
        item.storeLevel = item.storeLevel.toFixed(1)

      }
      arr.push(...res.data.rows)
      this.setData({
        commentList: arr,
        finished: res.data.lastPage,
        total: res.data.total
      })
    })
    this.setData({
      'appointment.storeId': options.id,
      section3SelectIndex: type || 0
    })
    API_Appointment.baseInfo({ storeId: options.id }).then(res => {
      let jso = res.data;
      let serviceList = jso.classifyList;
      let dateList = jso.daysArr;
      this.setData({ serviceList: serviceList, dateList: dateList });
      this.selectServiceIndex(0);
      this.selectWeekIndex(0);
    })
  },
  selectService: function (e) {
    let index = e.currentTarget.dataset.index;
    this.selectServiceIndex(index);
  },
  selectServiceIndex: function (index) {
    let serviceList = this.data.serviceList;
    let indexfor = 0;
    serviceList.forEach(item => {
      if (index == indexfor) {
        item.act = true;
        this.setData({ 'appointment.appointmentItem': item.name });
      } else {
        item.act = false;
      }
      indexfor++;
    })
    this.setData({ serviceList: serviceList });
  },

  sale(e) {
    var productId = e.currentTarget.dataset.id
    let that = this
    wx.navigateTo({
      url: '/pages/payConfig/payConfig?productId=' + productId,
    })
    /*API_Order.createOrder(params).then(res=>{
      if(res.success){
        wx.showToast({
          title: '购买成功',
        })
        wx.navigateTo({
          url: '/pages/myOrderList/myOrderList?state=wait_use&tabIndex=1',
  
        })
      }
    })*/
  },
  goTeach(e) {
    wx.navigateTo({
      url: '/pages/technicianDetail/technicianDetail?name=' + this.data.store.storeName + '&id=' + e.currentTarget.dataset.id,
    })
  },
  viewImg(e) {
    let src = this.data.opusList
    let arr = []
    for (let item of src) {
      arr.push(item.opusUrl)
    }
    wx.previewImage({
      current: e.currentTarget.dataset.src,
      urls: arr,
    })
  },
  callPhone() {
    let that = this
    wx.makePhoneCall({
      phoneNumber: that.data.store.storePhone + ''
    })
  },
  openMap() {
    let that = this
    wx.openLocation({
      latitude: that.data.store.latitude * 1,	//纬度
      longitude: that.data.store.longitude * 1, //经度
      name: that.data.store.location,	//目的地定位名称
      scale: 15,	//缩放比例
      address: that.data.store.addressName	//导航详细地址
    })
  },
  preview(event) {
    let currentUrl = event.currentTarget.dataset.src
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: event.currentTarget.dataset.srcs // 需要预览的图片http链接列表
    })
  },
  previewBac(event) {
    let currentUrl = event.currentTarget.dataset.src
    let that = this
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: that.data.bacImgs // 需要预览的图片http链接列表
    })
  },
  receive(e) {
    let type = e.currentTarget.dataset.type
    if (type === 'Y') {
      wx.showToast({
        title: '优惠券已领取',
        icon: 'none'
      })
      return
    }
    API_Coupon.receive(e.currentTarget.dataset.id).then(res => {
      let that = this
      wx.showToast({
        title: res.msg,
        duration: 2000,
        icon: 'none',
        success(e) {
          setTimeout(function () {
            //要延时执行的代码
            that.getMyCoupons(that.data.couponList)
          }, 2000) //延迟时间
        }
      })
    })
  },
  call() {
    wx.makePhoneCall({
      phoneNumber: this.data.store.storePhone + ''
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})